package com.yans.managers
{
	import com.yans.GlobalAPICore;
	import com.yans.interfaces.IImageApi;
	
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	
	import mx.graphics.codec.JPEGEncoder;
	
	public class ImageApi implements IImageApi
	{
		public function ImageApi()
		{
		}
		
		public function cut(source:BitmapData, path:String, quality:int = 60, size:int = 300, width:int = 467, height:int = 327):void {
			 
			var target:BitmapData = null;  
			var rect:Rectangle = null;
			var byteArr:ByteArray = null;
			var currentIndex:int = 0;
			var encoder:JPEGEncoder = new JPEGEncoder(quality);
			
			//				source.draw(img);
			for(var i:int = 0; i < (source.width / size) ; i++) {
				for(var j:int = 0; j < (source.height / size); j ++) {
					var Cwidth:Number = 0, Cheight:Number = 0;
					
					if(j == Math.floor(source.height / size)) {
						Cheight = source.height - j * size;
					}
					else {
						Cheight = size;
					}
					
					if(i == Math.floor(source.width / size)) {
						Cwidth = source.width - i * size;
					}
					else {
						Cwidth = size;
					}
					
					rect = new Rectangle(i * size, j * size, Cwidth, Cheight);
					target = new BitmapData(Cwidth, Cheight, true);
					
					
					target.copyPixels(source, rect, new Point);
					
					byteArr = encoder.encode(target);
					byteArr.position = 0;
					
					var fileName:String = j + "_" + i + ".jpg";// ++currentIndex + (rjpg.selected ? ".jpg" : ".png");
					//saveImg(fileName, byteArr);
					GlobalAPICore.fileManager.writeFile(path + "\\" + fileName, byteArr);
				}
			}
			
			//缩略图
			var w:Number, h:Number;
			var targetW:Number = width;
			var targetH:Number = height;
			var rate:Number = targetW / source.width;
			if(rate > targetH / source.height) {
				rate = targetH / source.height;
			}
			w = source.width * rate;
			h = source.height * rate;
			
			var bmptD:BitmapData = new BitmapData(w, h);
			var m:Matrix = new Matrix();
			m.scale(rate, rate);
			bmptD.draw(source, m);
			
			
//			saveImg("map.jpg", new JPEGEncoder(quality).encode(bmptD));
			GlobalAPICore.fileManager.writeFile(path + "\\pre.jpg",  encoder.encode(bmptD));
			
			target = null;  
			rect = null; 
			currentIndex = 0; 
		}
	}
}